// merchants/addProjectShare/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    title: '',
    projectType: 1, //1 充值卡,2 次卡,3 时效卡
    days: '',
    money: '',
    number: '',
    gradeid: 0, //股东等级id
    allianceid: 0,//联盟id
    flyerid: 0,//传单活动id
    showRule: false,
    ratio: '',//充值卡支付比例
    remark: '',
    detailpics: [],
    isEditor: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    if (options.cid) {
      this.getProject(options.cid);
      this.setData({
        id: options.cid
      })
    }
    if (options.gradeid) {
      this.setData({
        gradeid: options.gradeid
      })
    }
    if (options.allianceid) {
      this.setData({
        allianceid: options.allianceid
      })
    }
    if(options.flyerid){
      this.data.flyerid = options.flyerid;
    }
  },

  // 新增消费卡(股东礼包/联盟礼包)
  addOrUpdateHolderProject: function() {
    let that = this;
    let money = that.data.money;
    let number = that.data.number;
    let days = that.data.days;
    let discount = that.data.ratio;
    let param = {};
    let detailpics = that.data.detailpics;
    if (detailpics.length > 0) {
      for (var i = 0; i < detailpics.length; i++) {
        var Index = detailpics[i].lastIndexOf('l/');
        detailpics[i] = detailpics[i].substr(Index + 2, detailpics[i].length);
      }
    }
    detailpics = detailpics.toString();
    if (!that.data.title) {
      that.checkWrite('请输入消费卡名！');
      return
    }
    if (days=='') {
      days = 365;
    }
    if (discount==''){
      discount = 100;
    }
    if (money == '') {
      money = 0;
    }
    if (number == '') {
      number = 0;
    }
    param = {
      uid: app.globalData.userInfo.Uid,
      name: that.data.title,
      cardType: that.data.projectType,
      days: days,
      id: that.data.id, //消费卡项目id
      balance: money,
      number: number,
      discount: discount, 
      remark: that.data.remark,
      detailPics: detailpics
    }
    if (that.data.gradeid > 0) {
      param.isPackage = 1;
      param.gradeId = that.data.gradeid//股东等级id
    }
    if (that.data.allianceid > 0){
      param.allianceId = that.data.allianceid; //联盟id
    }
    if (that.data.flyerid > 0){
      param.isPackage = 1;
      param.gradeId = that.data.flyerid; //联盟id
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/Coupon/AddOrUpdateCardItem',
      data: param,
      method: 'POST',
      success: function(res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          wx.showToast({
            title: '添加成功',
            duration: 2000,
          })
          if(that.data.allianceid>0){
             wx.redirectTo({
               url: '/merchant/alliance/allianceManager/index?tagindex=3'
            })
          }else{
            wx.navigateBack({
              delta: 1
            })
          }

        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  // 获取消费卡信息
  getProject: function(id) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardItem?id=' + id,
      success: function(res) {
        if (res.data.Code == 0) {
          var detailpics = res.data.Data.DetailPics;
          var list = [];
          if (detailpics != '') {
            var newDetailPics = detailpics.split(",");
            for (let i = 0; i < newDetailPics.length; i++) {
              list[i] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[i];
            }
          }
          that.setData({
            title: res.data.Data.Name,
            projectType: res.data.Data.CardType,
            days: res.data.Data.Days,
            money: res.data.Data.DefaultBalance,
            number: res.data.Data.DefaultNumber,
            ratio: res.data.Data.Discount,
            remark: res.data.Data.Remark,
            detailpics: list
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  //填写判断
  checkWrite: function(str) {
    wx.showModal({
      title: '提示',
      content: str,
      showCancel: false
    })
  },

  clickRule: function () {
    this.setData({
      showRule: !this.data.showRule
    })
  },

  /**
 * 长按删除详细图片
 */
  deleteDetailPic: function (e) {
    var that = this;
    var newPics = that.data.detailpics;
    newPics.splice(e.currentTarget.dataset.index, 1);
    that.setData({
      detailpics: newPics
    })
  },

  /**
   * 上传详细图片
   */
  uploadDetailImage: function (e) { //这里是选取图片的方法
    var that = this;
    var detailPics = [];
    detailPics = that.data.detailpics
    var pics = [];
    if (detailPics.length >= 6) {
      wx.showToast({
        title: '最多选择6张！',
      })
      return;
    }
    wx.chooseImage({
      count: 6, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var imgs = res.tempFilePaths;
        for (var i = 0; i < imgs.length; i++) {
          pics.push(imgs[i])
        }
        that.uploadimgs({
          url: app.globalData.host + '/api/tool/upload?operation=uploadcouponimage', //这里是你图片上传的接口
          path: pics, //这里是选取的图片的地址数组
        });
      },
    })
  },
  //多张图片上传
  uploadimgs: function (data) {
    wx.showLoading({
      title: '提交中...',
      mask: true,
    })
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        success++;
        var str = resp.data
        var pic = JSON.parse(str);
        var pic_name = 'https://static.711688.net.cn/upload/coupondetail/' + pic.Data;
        var detailpics = that.data.detailpics;
        detailpics.push(pic_name);
        that.setData({
          detailpics: detailpics
        })
      },
      fail: (res) => {
        fail++;
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用     
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimgs(data);
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  bindtitle: function(e) {
    this.setData({
      title: e.detail.value
    })
  },
  selectType: function(e) {
    this.setData({
      projectType: e.currentTarget.dataset.type
    })
  },
  binddays: function(e) {
    this.setData({
      days: e.detail.value
    })
  },
  bindnumber: function(e) {
    this.setData({
      number: e.detail.value
    })
  },
  bindmoney: function(e) {
    this.setData({
      money: e.detail.value
    })
  },
  bindratio: function(e){
    this.setData({
      ratio: e.detail.value
    })
  },
  bindDescVal: function (e) {
    this.setData({
      remark: e.detail.value
    })
  }
})